<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: inc.prediction.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 
  function jl_prediction_show ($id, $task, &$my) {
    global $database;
    $connected_childs = array();
    $prediction = new JLPrediction($database);
    $prediction->load( $id );
    $prediction->set('admins',$prediction->getAdmins(true));
    $selected_childs = array();
    if ($pred_projects = $prediction->getChilds()) {
      foreach($pred_projects AS $project) {
        $selected_childs[]->value = $project['project_id'];
      }
    }

    if ($prediction->checked_out && $prediction->checked_out <> $my->id) {
      mosRedirect( JL_ADMIN_COMPONENT_LINK.'&adminmode='.JL_ADMIN_MODE, 'This Item has been checked out');
    }

     if ($id) {
       $prediction->checkout( $my->id );
     }
  
     $query = "SELECT name as text, id as value
                 FROM #__joomleague";
     $query .= " ORDER BY name";
     if (!$database->setQuery( $query )) echo $database->getErrorMsg(); 
     $predictions = $database->loadObjectList();
     // right now only one project per prediction is possible
     // will be changed as soon as combined prediction ranking is ready 
     $predictions_list = mosHTML::selectList( $predictions, 'projects[]', 'class="inputbox" size="1"','value', 'text', $selected_childs );
     /*
     $predictions_list = mosHTML::selectList( $predictions, 'projects[]', 'class="inputbox" size="auto"'
       .' multiple="multiple"','value', 'text', $selected_childs );
       */
     unset( $predictions );
     $append = 'class="inputbox" size="5" multiple="multiple"';
     
     $database->setQuery( "SELECT u.id AS value, u.name AS text, tm.user_id
                        FROM #__users u
                        LEFT JOIN #__joomleague_tip_members tm ON tm.user_id = u.id and tm.project_id = '".$prediction->id."'
                        WHERE tm.user_id IS NULL " );
     $tipp_admins = $database->loadObjectList();
     $tipadmin_list = mosHTML::selectList( $tipp_admins, 'tip_admin[]', $append, 'value', 'text', $prediction->admins );
     unset( $tipadmins );
     if ($task=='new') $prediction->init();
      $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_prediction.tpl.php';    
      require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';
    } 
      
    
    function  jl_prediction_save ($task) {
      global $database;
      $prediction_id = intval(mosGetParam($_REQUEST, 'id', 0));
      $prediction_name = mosGetParam($_REQUEST, 'name', '');
      $row = new JLPrediction( $database );
      if ($prediction_name != '') {
        $row->bind($_POST);
        $row->save($_POST, false);
      }
      if ($prediction_id==0) {
        $query = "SELECT id FROM #__joomleague_predictiongame WHERE
                name = '".$prediction_name."'";
        $database->setQuery($query);
        $database->query();
        $prediction_id=$database->loadResult();
      }
      $childs = mosGetParam($_REQUEST, 'projects', array());
      if ($prediction_id > 0 && $prediction_name != '') {
        $existing_childs = $row->getChilds(true);
        $to_delete = array_diff($existing_childs,$childs);
        if (count($to_delete) > 0) {
          foreach ($to_delete AS $delete) {
            $query = "DELETE FROM #__joomleague_predictiongame_project WHERE
                prediction_id = '".$prediction_id."' AND project_id = '".$delete."'";
            $database->setQuery($query);
            $database->query();
          }
        }
        $admins = mosGetParam($_REQUEST, 'tip_admin', array());
        $to_delete = array_diff($row->getAdmins(),$admins);
        if (count($to_delete) > 0) {
          foreach ($to_delete AS $delete) {
            $query = "DELETE FROM #__joomleague_predictiongame_admins WHERE
                prediction_id = '".$prediction_id."' AND user_id = '".$delete."'";
            $database->setQuery($query);
            $database->query();
          }
        }
      }
      foreach ($admins AS $admin) {
        $query = "INSERT IGNORE INTO #__joomleague_predictiongame_admins (user_id, prediction_id)
              VALUES ('".$admin."', '".$prediction_id."')";
        $database->setQuery($query);
        $database->query();
      }
      foreach ($childs AS $child) {
        $query = "INSERT IGNORE INTO #__joomleague_predictiongame_project (project_id, prediction_id)
              VALUES ('".$child."', '".$prediction_id."')";
        $database->setQuery($query);
        $database->query();
      }
      if ($task == 'apply')
        mosRedirect( JL_ADMIN_COMPONENT_LINK.'&task=edit&cid[0]='.$prediction_id.'&adminmode='.JL_ADMIN_MODE , 'Data have been Stored');
      elseif ($task ==  'save'){
        $row->checkin();
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&adminmode=".JL_ADMIN_MODE , 'Data have been Stored');
      }
    }
          

    function jl_prediction_cancel () {
      global $database;
      $row = new JLPrediction( $database );
	    $row->bind( $_POST );
	    $row->checkin();
	    mosRedirect( JL_ADMIN_COMPONENT_LINK."&adminmode=".JL_ADMIN_MODE );
	  }

      
    function jl_prediction_publish($id, &$my, $dowhat) {
      global $database;
      $row = new JLPrediction( $database );
      $row->publish($id, $dowhat, $my->id);
      mosRedirect(JL_ADMIN_COMPONENT_LINK.'&adminmode='.JL_ADMIN_MODE);
    }
      
    function jl_prediction_list($limit, $limitstart, &$my) {
      global $mainframe, $database;
        
      $database->setQuery( "SELECT count(*) FROM #__joomleague_predictiongame");
      $total = $database->loadResult();

      $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
      $database->setQuery( "SELECT pred.*, u.name AS checkoutuser
                             FROM #__joomleague_predictiongame AS pred
                             LEFT JOIN #__users AS u ON u.id = pred.checked_out
                             ORDER BY pred.name DESC
                             LIMIT $pageNav->limitstart,$pageNav->limit");
      $rows = $database->loadObjectList();
      $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_predictions.tpl.php';    
      require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';         
    }

    function jl_prediction_remove(&$cid) {
      global $database;
      $row = new JLPrediction( $database );
		  foreach($cid as $cids) {
	      $row->delete($cids);
        $query=sprintf("DELETE FROM #__joomleague_predictiongame_admins WHERE prediction_id = '%s'",$cids);
        $database->setQuery($query);
    		$database->query();
    		echo $query.'<br />';
    		$query=sprintf("DELETE FROM #__joomleague_predictiongame_project WHERE prediction_id = '%s'",$cids);
    		$database->setQuery($query);
    		$database->query();
    		echo $query.'<br />';
      }
      $query="OPTIMIZE TABLE #__joomleague_predictiongame_admins\n
    						FLUSH TABLE #__joomleague_predictiongame_admins";
    	$database->setQuery($query);
    	$database->query();
    	echo $query.'<br />';
    	$query="OPTIMIZE TABLE #__joomleague_predictiongame_project\n
    						FLUSH TABLE #__joomleague_predictiongame_project";
    	$database->setQuery($query);
    	$database->query();
    	echo $query.'<br />';
  }
?>